package com.upsuns.aio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

import com.upsuns.util.Constants;

/**
 *@Description:<p>连接远程服务器回调处理器</p>
 *@author 王旭
 *@time 2016年3月17日 下午11:28:13
 */
public class ConnectCompletionHandler implements CompletionHandler<Void, CountDownLatch>{
	
	private AsynchronousSocketChannel sc;

	public ConnectCompletionHandler() {}
	
	public ConnectCompletionHandler(AsynchronousSocketChannel sc) {
		this.sc = sc;
	}
	
	@Override
	public void completed(Void result, CountDownLatch attachment) {
		byte[] req = Constants.TIME_QUERY.getBytes();
		ByteBuffer reqBuffer = ByteBuffer.allocate(req.length);
		reqBuffer.put(req);
		reqBuffer.flip();
		sc.write(reqBuffer, reqBuffer, new CompletionHandler<Integer, ByteBuffer>() {

			@Override
			public void completed(Integer result, ByteBuffer buffer) {
				if(buffer.hasRemaining()) //没写完继续
					sc.write(buffer, buffer, this);
				else { //发送完请求读取服务端响应
					ByteBuffer readBuffer = ByteBuffer.allocate(1024);
					sc.read(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>() {

						@Override
						public void completed(Integer result,
								ByteBuffer readedBuffer) {
							readedBuffer.flip();
							byte[] respBytes = new byte[readedBuffer.remaining()];
							readedBuffer.get(respBytes);
							try {
								String respStr = new String(respBytes, "utf-8");
								System.out.println("响应信息：" + respStr);
								
								try {
									sc.close();
									attachment.countDown();
								} catch (IOException e) {
									e.printStackTrace();
								}
								
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
						}

						@Override
						public void failed(Throwable exc, ByteBuffer buffer) {
							try {
								sc.close();
								attachment.countDown();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
						
					});
				}
			}

			@Override
			public void failed(Throwable exc, ByteBuffer buffer) {
				try {
					sc.close();
					attachment.countDown();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		});
	}

	@Override
	public void failed(Throwable exc, CountDownLatch attachment) {
		try {
			sc.close();
			attachment.countDown();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	

}
